/**
 * @author dtran
 * Date Created: 6/25/2014
 * Description: This class is use to track user session using Servlet Filter and redirect them
 * 				to the login page if sessions is already invalidated.
 */


package com.movieproject.service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {
	
	private ArrayList<String> urlList;
	
	public void destroy() {
		
	}
	
	/**
	 * This called for each request for our application. Hence we can check the session in this method and see if it is
	 * valid. 
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		// Get the current path		
		String url = request.getServletPath();
		boolean allowedRequest = false;
		
		if(urlList.contains(url)) {
			allowedRequest = true;
		}
		
		if (!allowedRequest) {
			// This will check if a session already existed for the request or not. 
			// If exist, return the existed session
			HttpSession session = request.getSession(false);
			
			if (null == session) {							// if no session exist previously, create one.
				session = request.getSession(true);
				Integer sessID = new Integer(0);
				session.setAttribute("sessID", sessID);
			} else {
				// if session exist, check for current id
				Integer logged = (Integer) session.getAttribute("sessID");
				if (logged == null) {		// if id no longer exist, redirect to login page
					response.sendRedirect("Login");
				} else {					// increment sessID
					logged = logged.intValue() + 1;
					session.setAttribute("sessID", logged);
				}
			}
		}
		
		chain.doFilter(request, response);
	}
	
	/**
	 * This method get called by the servlet container and will get FilterConfig object as arguement.
	 * From this config object, we read the init parameters. 
	 */
	public void init(FilterConfig config) throws ServletException {
		String urls = config.getInitParameter("avoid-urls");
		StringTokenizer token = new StringTokenizer(urls, ",");
		
		urlList = new ArrayList<String>();
		
		while (token.hasMoreTokens()) {
			urlList.add(token.nextToken());
		}
	}

}
